/**
 * @file ordersSlice.js
 * @description 后台管理系统的订单管理 Redux slice
 */
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  orders: [],       // 所有订单列表
  isLoading: false,
  error: null,
};

const ordersSlice = createSlice({
  name: 'orders',
  initialState,
  reducers: {
    /**
     * 开始加载订单
     * @param {object} state - 当前的 state
     */
    loadOrdersStart: (state) => {
      state.isLoading = true;
      state.error = null;
    },
    /**
     * 订单加载成功
     * @param {object} state - 当前的 state
     * @param {object} action - Redux action，action.payload 应该是订单数组
     */
    loadOrdersSuccess: (state, action) => {
      state.isLoading = false;
      state.orders = action.payload;
    },
    /**
     * 订单加载失败
     * @param {object} state - 当前的 state
     * @param {object} action - Redux action，action.payload 应该是错误信息
     */
    loadOrdersFailure: (state, action) => {
      state.isLoading = false;
      state.error = action.payload;
    },
    /**
     * 更新订单状态
     * @param {object} state - 当前的 state
     * @param {object} action - Redux action，action.payload 应该包含 orderId 和更新的字段
     */
    updateOrderStatus: (state, action) => {
      const { orderId, status } = action.payload;
      const orderIndex = state.orders.findIndex(order => order.orderId === orderId);
      if (orderIndex !== -1) {
        state.orders[orderIndex].status = status;
        
        // 同步更新到 localStorage
        try {
          const allOrders = JSON.parse(localStorage.getItem('userOrders')) || [];
          const storageOrderIndex = allOrders.findIndex(order => order.orderId === orderId);
          if (storageOrderIndex !== -1) {
            allOrders[storageOrderIndex].status = status;
            localStorage.setItem('userOrders', JSON.stringify(allOrders));
          }
        } catch (error) {
          console.error("更新订单状态到localStorage失败:", error);
        }
      }
    },
  },
});

export const {
  loadOrdersStart,
  loadOrdersSuccess,
  loadOrdersFailure,
  updateOrderStatus,
} = ordersSlice.actions;

/**
 * 异步 action creator 用于加载所有订单
 * @returns {Function} 一个 thunk 函数
 */
export const fetchAllOrders = () => async (dispatch) => {
  dispatch(loadOrdersStart());
  try {
    // 从 localStorage 获取所有订单
    const allOrders = JSON.parse(localStorage.getItem('userOrders')) || [];
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    dispatch(loadOrdersSuccess(allOrders));
  } catch (error) {
    console.error("加载订单失败:", error);
    dispatch(loadOrdersFailure(error.toString()));
  }
};

/**
 * 异步 action creator 用于更新订单状态
 * @param {string} orderId - 订单ID
 * @param {string} status - 新的订单状态
 * @returns {Function} 一个 thunk 函数
 */
export const updateOrder = (orderId, status) => async (dispatch) => {
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    dispatch(updateOrderStatus({ orderId, status }));
    return true;
  } catch (error) {
    console.error("更新订单状态失败:", error);
    return false;
  }
};

export default ordersSlice.reducer;